package com.manager.user.module;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.manager.commons.log.LogFactory;
import com.manager.core.module.manager.service.LoginService;
import com.manager.core.shiro.core.entity.LoginUser;
import com.manager.core.web.json.AjaxJson;

/**
 * 控制器
 * @author H
 * @date 2023-10-08
 * @version 1.0
 */
@Controller
public class LoginController {

	protected static final Logger logger = LogFactory.getLogger(LoginController.class);

	@Autowired
	private LoginService _service;


	/**
	 * 登录[post]
	 * 
	 * @return
	 */
	@PostMapping(value = "/login")
	public @ResponseBody AjaxJson dLogin(LoginUser loginUser, HttpSession session, HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		try {
			try {
				return _service.doLogin(loginUser, session, request, subject);
			} catch (AuthenticationException e) {
				e.printStackTrace();
				// 认证失败
				if (e instanceof UnknownAccountException) {
					logger.info(loginUser.getAccount() + "认证失败，用户不存在！");
				} else if (e instanceof IncorrectCredentialsException) {
					logger.info(loginUser.getAccount() + "认证失败，密码不正确！");
				} else if (e instanceof LockedAccountException) {
					logger.info(loginUser.getAccount() + "认证失败，账号已被冻结！");
				}
				// 在js前端会主动刷新验证码，此处将验证码移出，是防止js刷新失败
//				session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
				subject.logout();
				return new AjaxJson("用户名或密码错误！");
			}
		} catch (Exception e) {
			subject.logout();
			// 在js前端会主动刷新验证码，此处将验证码移出，是防止js刷新失败
//			session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			return new AjaxJson("服务异常，请稍后再试！");
		}
	}
}